# -*- coding: utf-8 -*-
# -*- frozen_string_literal: true -*-

require "tmpdir"
require "tempfile"
require_relative "./../../_config/minitest"
require_relative "./../../../dev/tasks/prep_release"

# test dependency:
require "sdbm"

class TestPrepRelease < Minitest::Test
  def test_can_build_gem_without_warnings
    skip "Integration: Building gems takes too long" unless ENV["LORCA_ALL_TESTS"]
    _, err = capture_subprocess_io { LorcaPrepRelease.package }
    refute_match %r/warning/i, err
  end

  def test_imports_eff_wordlist
    wordlist = File.expand_path "./../../../_fixtures/dev/wordlist.txt", __FILE__

    Dir.mktmpdir do |dir|
      LorcaPrepRelease.import_wordlist wordlist, to: dir
      imported = "#{dir}/wordlist"

      # no need to replace it with Lorca. The point is to check the wordlist got
      # imported not that Lorca can read it.
      SDBM.open(imported, 0444) { |db| assert_equal "c", db.fetch("11113") }
    end
  end

  def test_generates_checksum_for_packed_gem
    expected_checksum =
      "bb95b01232696ce38a4ca482aebc5b7037744621eddb37071e543ad55c38db0c"\
      "ba0317f089916576b52f3eaddfac0dd3495057ce0fc415032bab04ef3539d2ee"

    Dir.mktmpdir do |_|
      gem = Tempfile.new.tap{ |g| g.write "ah" }.tap(&:close)

      checksum = LorcaPrepRelease.checksum gem, archive: _
      assert_equal expected_checksum, checksum
    end
  end

  def test_writes_checksum_to_given_directory
    Dir.mktmpdir do |dir|
      tempfile = Tempfile.new
      basename = File.basename tempfile

      LorcaPrepRelease.checksum tempfile, archive: dir
      assert File.exist?("#{dir}/#{basename}.sha512"), "Missing checksum"
    end
  end

  def test_fails_to_commit_checksum_when_checksum_missing
    Dir.mktmpdir do |dir|
      e = assert_raises { LorcaPrepRelease.commit_checksum archive: dir }
      assert_equal "Must create checksum file before trying to do commit",
        e.message
    end
  end

  def test_fails_to_tag_release_commit_when_checksum_missing
    Dir.mktmpdir do |dir|
      e = assert_raises { LorcaPrepRelease.tag_release_commit archive: dir }
      assert_equal "Must add checksum before tagging a release", e.message
    end
  end

  def test_publishes_gem
    assert_respond_to LorcaPrepRelease, :publish_gem
  end
end
